package org.jiang.springbootdemo.demos.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadConfig {

    //线程池维护线程的最少数量
    @Value("${threaPool.corePoolSize}")
    private Integer corePoolSize;
    //允许的空闲时间
    @Value("${threaPool.keepAliveSeconds}")
    private Integer keepAliveSeconds;
    //线程池维护线程的最大数量
    @Value("${threaPool.maxPoolSize}")
    private Integer maxPoolSize;
    //缓存队列
    @Value("${threaPool.queueCapacity}")
    private Integer queueCapacity;

    @Value("${threaPool.thread-name-prefix}")
    private String threadNamePrefix;

    @Bean(name = "taskExecutor")
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        //spring提供的ThreadPoolTaskExecutor 线程池，是有setThreadNamePrefix() 方法的。
        //jdk 提供的ThreadPoolExecutor 线程池是没有 setThreadNamePrefix() 方法的
        executor.setThreadNamePrefix(threadNamePrefix);
        ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
        executor.setRejectedExecutionHandler(callerRunsPolicy);
        executor.initialize();
        return executor;
    }

}


